const Koa = require("koa");
const route = require("koa-route");
const app = new Koa();
const MyTestParent = require("./my-test-parent");
const myTest = require("./my-test");

const main = (ctx) => {
  ctx.response.body = "Hello World!";
};

let result = [];
let returnCount = 0;
startRun = (val1, val2) => {
  result = [] 
  return new Promise((resolve, reject) => {
    returnCount = 0;
    new MyTestParent().fib(val1).then((rv1) => {
      console.log("---->task1 end, rv1:", rv1);
      result.push(rv1);
      returnCount++;
      if (returnCount > 1) {
        resolve(result);
      }
    });

    new MyTestParent().fib(val2).then((rv2) => {
      console.log("---->task2 end, rv2:", rv2);
      result.push(rv2);
      returnCount++;
      if (returnCount > 1) {
        resolve(result);
      }
    });

    console.log("---->generatePrimes end");
  });
};

testAsyncRun = async (ctx) => {
  console.log(`parent process is pid ${process.pid}`);
  console.log("---->testAsyncRun start");
  const startTime = new Date().getTime();
  let result = await startRun(44, 45);
  let endTime = new Date().getTime();
  costTime = endTime - startTime;
  console.log("---->testAsyncRun end, result:" + result + " costTime:" + costTime);
  ctx.response.body = `并行计算素数完成,耗时${costTime}\n 结果：\n ${result}`;
};

testRun = (ctx) => {
  console.log("---->testRun start");
  const startTime = new Date().getTime();
  let rv1 = myTest.fib(44);
  let rv2 = myTest.fib(45);
  result.push(rv1);
  result.push(rv2);
  let endTime = new Date().getTime();
    costTime = endTime - startTime;
    console.log("---->testRun end, result:" + result + " costTime:" + costTime);
  ctx.response.body = `计算完成,耗时${costTime}\n 结果：\n ${result}`;
};

app.use(route.get("/test-async", testAsyncRun));
app.use(route.get("/test", testRun));
app.use(route.get("/", main));
console.log("start listen 3000");
app.listen(3000);
